import { defineStore } from 'pinia';
import { ref, watch, onMounted } from 'vue';
import { VxeUI } from 'vxe-table';

export const useThemeStore = defineStore('theme', () => {
    const isDark = ref(false); // 默认是亮色模式

    // 切换暗黑模式
    const toggleDarkMode = () => {
        isDark.value = !isDark.value; // 切换状态
        localStorage.setItem('theme', isDark.value ? 'dark' : 'light');
    };

    // 检查系统主题偏好并设置初始状态
    const checkSystemTheme = () => {
        const savedTheme = localStorage.getItem('theme');
        if (savedTheme) {
            isDark.value = savedTheme === 'dark';
        } else {
            isDark.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
        }
    };

    // 监听主题切换并应用到 VxeUI
    watch(
        isDark,
        (newVal) => {
            VxeUI.setTheme(newVal ? 'dark' : 'light'); // 切换主题
        },
        { immediate: true } // 页面加载时立即应用当前主题
    );

    onMounted(() => {
        checkSystemTheme(); // 页面加载时检查并设置主题
    });

    return { isDark, toggleDarkMode };
});
